const Controller = require('egg').Controller;
const bcrypt = require('bcrypt');
const queryString = require('query-string');

class UserController extends Controller {

  async update() {
    const body = this.ctx.request.body;
    delete body._csrf;

    if (body.id != '')
      body.id = Number(body.id);

    try {
      this.ctx.validate({
        phoneNumber: { type: 'string' },
        password: { type: 'string', allowEmpty: true },
        task: { type: 'string' },
        id: { type: 'int' }
      }, body);
    } catch (err) {
      var message = '';
      err
        .errors
        .map(function (item) {
          message += item.field + ' ' + item.message + '&#10';
        });

      const location = '/page/message?' + queryString.stringify({
        status: "warn",
        title: "用户记录修改失败",
        message: message,
        backTitle: '返回用户列表',
        backPage: "/page/userList"
      }
      );

      this.ctx.body = { location };
      return;
    }

    if (body.isUser == 'on') {
      const user = await this.app.mysql.get('user', { id: body.id });
      let authArr = user.auth.split(',');
      authArr = authArr.filter(item => item.indexOf('task') == -1);
      authArr.push(body.task == '老师' ? "task" : "task-common");
      const auth = authArr.join(',');

      const userUpdate = {
        id: body.id,
        phoneNumber: body.phoneNumber,
        auth
      };

      if (body.password != '')
        userUpdate.encryptedPassword = await bcrypt.hash(body.password, 5);

      const result = await this.app.mysql.update('user', userUpdate);

      if (result.affectedRows == 1) {
        const location = '/page/message?' + queryString.stringify({
          status: "success",
          title: "用户更新成功",
          message: '用户' + user.name + '更新成功',
          backTitle: '返回用户列表',
          backPage: "/page/userList"
        });

        this.ctx.body = { location };
        return;
      } else {
        const location = '/page/message?' + queryString.stringify({
          status: "warn",
          title: "用户更新失败",
          message: '未知错误',
          backTitle: '返回用户列表',
          backPage: "/page/userList"
        });

        this.ctx.body = { location };
        return;
      }

    } else {
      const user = await this.app.mysql.get('user', { id: body.id });
      const result = await this.app.mysql.delete('user', { id: body.id });

      if (result.affectedRows == 1) {
        const location = '/page/message?' + queryString.stringify({
          status: "success",
          title: "用户更新成功",
          message: '用户' + user.name + '更新成功',
          backTitle: '返回用户列表',
          backPage: "/page/userList"
        });

        this.ctx.body = { location };
        return;
      } else {
        const location = '/page/message?' + queryString.stringify({
          status: "warn",
          title: "用户更新失败",
          message: '未知错误',
          backTitle: '返回用户列表',
          backPage: "/page/userList"
        });

        this.ctx.body = { location };
        return;
      }

    }

  }

  async create() {
    const body = this.ctx.request.body;
    delete body._csrf;

    if (body.id != '')
      body.id = Number(body.id);

    try {
      this.ctx.validate({
        isUser: { type: 'string' },
        phoneNumber: { type: 'string' },
        password: { type: 'string' },
        task: { type: 'string' },
        id: { type: 'int' }
      }, body);
    } catch (err) {
      var message = '';
      err
        .errors
        .map(function (item) {
          message += item.field + ' ' + item.message + '<br>';
        });

      const location = '/page/message?' + queryString.stringify({
        status: "warn",
        title: "失败",
        message: message,
        backTitle: '返回用户列表',
        backPage: "/page/userList"
      });

      this.ctx.body = { location };

      return;
    }

    if (body.isUser == 'on') {
      const member = await this.app.mysql.get('member', { id: body.id });
      const encryptedPassword = await bcrypt.hash(body.password, 5);
      const authArr = [];

      if (body.task == '老师') {
        authArr.push('task');
      } else if (body.task == '学生') {
        authArr.push('task-common');
      };

      const userCreate = {
        phoneNumber: body.phoneNumber,
        auth: authArr.join(','),
        memberId: body.id,
        name: member.netName,
        encryptedPassword,
        isAdmin: 0
      };


      const lastUserId = await this.app.mysql.query(`SELECT MAX(id) FROM user;`);
      userCreate.id = lastUserId[0]['MAX(id)'] + 1;
      const result = await this.app.mysql.insert('user', userCreate);

      if (result.affectedRows == 1) {
        const location = '/page/message?' + queryString.stringify({
          status: "success",
          title: "用户创建成功",
          message: '用户' + member.netName + '创建成功',
          backTitle: '返回用户列表',
          backPage: "/page/userList"
        });

        this.ctx.body = { location };
        return;
      } else {
        const location = '/page/message?' + queryString.stringify({
          status: "warn",
          title: "用户创建失败",
          message: '未知错误',
          backTitle: '返回用户列表',
          backPage: "/page/userList"
        });

        this.ctx.body = { location };
        return;
      }

    } else {

      const location = '/page/message?' + queryString.stringify({
        status: "warn",
        title: "用户创建失败",
        message: '没有选择创建用户',
        backTitle: '返回用户列表',
        backPage: "/page/userList"
      });

      this.ctx.body = { location };
      return;

    }



  }
}

module.exports = UserController;
